package window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * 滑动窗口 指定延迟时间
 */
public class EventTimeSlidingWindowDemo {

    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple2<Long, Integer>> mapped = lines.map(new MapFunction<String, Tuple2<Long, Integer>>() {
            @Override
            public Tuple2<Long, Integer> map(String s) throws Exception {
                String[] fields = s.split(",");
                return Tuple2.of(Long.parseLong(fields[0]), Integer.parseInt(fields[1]));
            }
        });

        // watermark
        SingleOutputStreamOperator<Tuple2<Long, Integer>> watermark = mapped.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple2<Long, Integer>>(Time.seconds(2)) {
            @Override
            public long extractTimestamp(Tuple2<Long, Integer> t) {
                return t.f0;
            }
        });

        // 划分窗口
        AllWindowedStream<Tuple2<Long, Integer>, TimeWindow> window = watermark.windowAll(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(5)));

        // 聚合
        SingleOutputStreamOperator<Tuple2<Long, Integer>> summed = window.sum(1);

        // 打印
        summed.print();

        env.execute("Sliding Window");
    }
}
